package com.duck.duckchatbackend.websocket;

import com.duck.duckchatbackend.entity.dto.MessageSendDto;
import com.duck.duckchatbackend.utils.JsonUtils;
import com.mysql.cj.protocol.MessageSender;
import org.redisson.Redisson;
import org.redisson.api.RTopic;
import org.redisson.api.RedissonClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.lang.ref.WeakReference;
import java.text.SimpleDateFormat;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @BelongsProject: DuckChatBackend
 * @BelongsPackage: com.duck.duckchatbackend.websocket
 * @Author: liyajun
 * @CreateTime: 2024-12-01  22:10
 * @Description: 消息处理器，基于redis实现的消息队列
 * @Version: 1.0
 */
@Component("messageHandler")
public class MessageHandler {
   private static final Logger logger = LoggerFactory.getLogger(MessageHandler.class);
   private static  final  String MESSAGE_TOPIC = "message.topic";
   @Resource
   private RedissonClient redissonClient;
   @Resource
   private ChannelContextUtils channelContextUtils;

   @PostConstruct
   public void listMessage(){
      // 订阅消息
      RTopic rTopic = redissonClient.getTopic(MESSAGE_TOPIC);
      rTopic.addListener(MessageSendDto.class,(MessageSendDto,sendDto)->{
         logger.info("收到广播消息:{}", JsonUtils.convertObj2Json(sendDto));
         channelContextUtils.sendMessage(sendDto);
      });
   }
   public void sendMessage(MessageSendDto sendDto){
       //channelContextUtils.sendMsg();
       // 往该主题发送消息
       RTopic rTopic = redissonClient.getTopic(MESSAGE_TOPIC);
       rTopic.publish(sendDto);
      ReentrantLock lock = new ReentrantLock();
   }
}


